<template>
  <section class="todoapp">
   
<HeaderComponent
@addList='addList'></HeaderComponent>
<BodyComponent 
:list='renderList'
@selectAll='selectAll'
@delList='delList'
@changeShow='changeShow'
@changeValue='changeValue'></BodyComponent>
<FooterComponent
:sum='sum'
:showBtn='showBtn'
@delOverBtn='delOverBtn'
:type='type'
@change='change'></FooterComponent>

    
  </section>
</template>

<script>
import HeaderComponent from './components/headerComponent.vue'
import BodyComponent from './components/bodyComponent.vue'
import FooterComponent from './components/footerComponent.vue'
export default {
  components:{
    HeaderComponent,
    BodyComponent,
    FooterComponent,
  },
  data(){
    return{
      list:JSON.parse(localStorage.getItem('list'))||[
        {
        id:1,
        value:'读万卷书',
        flag:true,
        showInput:false,
      },
       {
        id:2,
        value:'行万里路',
        flag:false,
        showInput:false,
      },
      ],
      type:'all',
    }
  },
  methods:{
    selectAll(flag){
      this.list.forEach(item=>item.flag=flag)
    },
    addList(value){
      this.list=[...this.list,{
        id:+new Date(),
        value:value,
        flag:false,
      }]
    },
    delList(id){
     const event=this.list.find(item=>item.id===id)
     if(!event.flag) return alert('未完成的事件不能删除哦！')
      this.list=this.list.filter(item=> item.id!==id)
    },
    delOverBtn(){
      this.list=this.list.filter(item=>!item.flag)
    },
    change(type){
      this.type=type
    },
    changeShow(id){
      console.log(1);
      this.list.forEach(item=>{
        if(item.id===id)
        {if(item.flag) return alert('已完成的事件不能修改')
          item.showInput=true
        }
      })
    },
    changeValue(value,id){
      this.list.forEach(item=>{
        if(item.id===id){
          item.value=value
          item.showInput=false
        }
      })
    }
  },
  computed:{
    sum(){
      return this.list.filter(item=>!item.flag).length
    },
    showBtn(){
      return this.list.some(item=>item.flag)
    },
    renderList(){
      switch(this.type){
        case 'all':
          return this.list
        case 'active':
          return this.list.filter(item=>!item.flag)
        case 'completed':
          return this.list.filter(item=>item.flag)
        default:
          return this.list
      }
    }
  },
watch:{
  list:{
    deep:true,
    handler(newVal){
      localStorage.setItem('list',JSON.stringify(newVal))
    }
  }
}
}

</script>

<style></style>
